# coding:utf-8
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QFileDialog, QWidget
from qfluentwidgets import FluentIcon as FIF
from qfluentwidgets import (SettingCardGroup, SwitchSettingCard, OptionsSettingCard, PushSettingCard, BodyLabel,
                            setFont, CustomColorSettingCard, setTheme, setThemeColor, ScrollArea, ExpandLayout)

from common import cfg, signalBus, workerRequest, isWin11
from components import Alert
from server.api import LenovoAPI


class SettingInterface(ScrollArea):
    """ 设置界面 """

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.scrollWidget = QWidget()
        self.expandLayout = ExpandLayout(self.scrollWidget)

        # 设置标签
        self.settingLabel = BodyLabel(self.tr("设置"), self)
        # 个性化
        self.personalGroup = SettingCardGroup('界面设置', self.scrollWidget)
        self.micaCard = SwitchSettingCard(
            FIF.TRANSPARENT,
            '云母效果',
            '',
            cfg.micaEnabled,
            self.personalGroup
        )
        self.themeCard = OptionsSettingCard(
            cfg.themeMode,
            FIF.BRUSH,
            '主题',
            '',
            texts=['光亮', '黑暗', '使用系统设置'],
            parent=self.personalGroup
        )
        self.themeColorCard = CustomColorSettingCard(
            cfg.themeColor,
            FIF.PALETTE,
            '主题颜色',
            '',
            self.personalGroup
        )
        self.zoomCard = OptionsSettingCard(
            cfg.dpiScale,
            FIF.ZOOM,
            '界面缩放',
            '',
            texts=["100%", "125%", "150%", "175%", "200%", "使用系统设置"],
            parent=self.personalGroup
        )

        # 缓存设置
        self.cacheGroup = SettingCardGroup('缓存设置', self.scrollWidget)
        # 下载目录
        self.downloadFolderCard = PushSettingCard(
            '选择文件夹',
            FIF.DOWNLOAD,
            '下载目录',
            cfg.get(cfg.downloadFolder),
            self.cacheGroup
        )
        # 联想 token
        self.lenovoTokenCard = PushSettingCard(
            '重新获取token',
            FIF.TAG,
            'Lenovo Token',
            cfg.get(cfg.lenovoToken),
            self.cacheGroup
        )

        self.__initWidget()

    def __initWidget(self):
        self.setViewportMargins(0, 80, 0, 20)
        self.setObjectName('SettingInterface')
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.setViewportMargins(0, 120, 0, 20)
        self.setWidget(self.scrollWidget)
        self.setWidgetResizable(True)
        setFont(self.settingLabel, 33)
        self.enableTransparentBackground()

        self.micaCard.setEnabled(isWin11())
        # 初始化文本
        self.themeColorCard.defaultRadioButton.setText("默认颜色")
        self.themeColorCard.customRadioButton.setText("自定义颜色")
        self.themeColorCard.customLabel.setText("自定义颜色")
        self.themeColorCard.chooseColorButton.setText("选择颜色")

        # 初始化布局
        self.__initLayout()
        self.__connectSignalToSlot()

    def __initLayout(self):
        self.settingLabel.move(36, 30)

        self.personalGroup.addSettingCards(
            [self.micaCard, self.themeCard, self.themeColorCard, self.zoomCard]
        )
        self.cacheGroup.addSettingCards(
            [self.downloadFolderCard, self.lenovoTokenCard]
        )

        # 添加设置卡组到布局中
        self.expandLayout.setSpacing(28)
        self.expandLayout.setContentsMargins(36, 10, 36, 0)
        self.expandLayout.addWidget(self.personalGroup)
        self.expandLayout.addWidget(self.cacheGroup)

    def __connectSignalToSlot(self):
        """
        连接信号到插槽
        :return:
        """
        cfg.appRestartSig.connect(self.__showRestartTooltip)
        # 个性化
        cfg.themeChanged.connect(setTheme)
        self.themeColorCard.colorChanged.connect(setThemeColor)
        self.micaCard.checkedChanged.connect(signalBus.micaEnableChanged)

        self.downloadFolderCard.clicked.connect(self.__onDownloadFolderCardClicked)
        self.lenovoTokenCard.clicked.connect(self.__onLenovoTokenCardClickedClick)

    def __showRestartTooltip(self):
        """ 显示重启工具提示 """
        Alert.success('重启后配置生效')

    def __onDownloadFolderCardClicked(self):
        """
        点击插槽下载文件夹卡
        :return:
        """
        folder = QFileDialog.getExistingDirectory(self, self.tr("选择文件夹"), cfg.get(cfg.downloadFolder))
        if not folder or cfg.get(cfg.downloadFolder) == folder:
            return

        cfg.set(cfg.downloadFolder, folder)
        self.downloadFolderCard.setContent(folder)

    def __onLenovoTokenCardClickedClick(self):
        def lenovoTokenFetched(token: str):
            self.lenovoTokenCard.setContent(token)
            Alert.success('Token已更新')

        workerRequest(LenovoAPI.get_token, slot=lenovoTokenFetched)
